package ArrayDemo;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 * 示例 1：
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 */
public class demo14 {
    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        Solution solution = new Solution();
        String result = solution.longestCommonPrefix(strs);
        System.out.println(result);
    }

    static class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            for (int index = 0; index < strs[0].length(); index++) {
                char st = strs[0].charAt(index);
                for (int i = 1; i < strs.length; i++) {
                    if(index+1>strs[i].length()){
                        return strs[0].substring(0, index);
                    }
                    if (strs[i].charAt(index) == st && index < strs[i].length()) {
                    } else {
                        return strs[0].substring(0, index);
                    }
                }
            }
            return strs[0].substring(0, strs[0].length());
        }
    }
}

